
// 前端ui模块表，用来存储定制化的 首页、详情页

package misc

import (
	//"fmt"
	"errors"
	"strings"
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

func init() {
	orm.RegisterModel(new(Uimods))
}

type Uimods struct {
	UimodsId     int64      `orm:"column(uimods_id);pk;auto" json:"uimods_id" form:"uimods_id"`  //自增Id
	PartnerId    int64        `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"` //文件的父ID
	StoreId      int64        `orm:"column(store_id)" json:"store_id" form:"store_id"`         //门店
	AppId        string     `orm:"column(app_id);size(32);index" json:"app_id" form:"app_id"`       //微信ID
	Ctype        string     `orm:"column(ctype);size(32);index" json:"ctype" form:"ctype"`         //c=个人类型、b=企业类型
	Types        string     `orm:"column(types);size(32);index" json:"types" form:"types"`         //模块类型：home=首页，detail=详情页
	Title        string     `orm:"column(title);size(100)" json:"title" form:"title"`       //标题
	Name         string     `orm:"column(name);size(64);unique" json:"name" form:"name"`            //模块名字
	SubType      string     `orm:"column(subtype);null" json:"subtype" form:"subtype"`      //模块子类型
	Data         string     `orm:"column(data);type(text)" json:"data" form:"data"`      //模块数据
	Dft          int8       `orm:"column(dft);default(1)" json:"dft" form:"dft"`         //默认1：1:非默认，2:必选模块
	Sort         int        `orm:"column(sort);default(0)" json:"sort" form:"sort"`      
	CreatedAt    time.Time  `orm:"column(created_at);auto_now_add;type(datetime)" json:"-"`
	CreatedAtStr string     `orm:"-" json:"created_at"`
	UpdatedAt    time.Time  `orm:"column(updated_at);auto_now;type(datetime)" json:"-"`
	UpdatedAtStr string     `orm:"-" json:"updated_at"`
	Note         string     `orm:"column(note);size(1024);null" json:"note" form:"note"`   //备注
}

func CreateUimods(uimods *Uimods) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(uimods)
	return
}

func GetUimodsByAppId(appId string) (uimods *Uimods, err error) {
	o := models.GetDefaultDB()
	uimods = &Uimods{AppId: appId}
	if err = o.Read(uimods, "AppId"); err != nil {
		return
	}
	return
}

func GetAllUimodss(storeIds []int64,query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*Uimods, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Uimods))
	if start, ok := query["start_created"]; ok {
		if startTime, err := time.Parse(consts.DATELINKTIME_FORMAT, start); err == nil {
		    qs = qs.Filter("created_at__gte", startTime)
		}
		delete(query, "start_created")
	}
	if end, ok := query["end_created"]; ok {
		if endTime, err := time.Parse(consts.DATELINKTIME_FORMAT, end); err == nil {
	        qs = qs.Filter("created_at__lte", endTime)
	    }
		delete(query, "end_created")
	}
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	if len(storeIds) > 0 {
        qs = qs.Filter("store_id__in", storeIds)
    }
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Uimods
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, uimod := range lists {
			uimod.CreatedAtStr = uimod.CreatedAt.Format(consts.DATETIME_FORMAT)
            uimod.UpdatedAtStr = uimod.UpdatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateUimodsById(m *Uimods, fields ...string) error {
	o := models.GetDefaultDB()
	v := Uimods{UimodsId: m.UimodsId}
	if err := o.Read(&v); err != nil {
		return err
	}
	_, err := o.Update(m, fields...)
	return err
}

func UpdateUimodsByAppId(m *Uimods, fields ...string) error {
	o := models.GetDefaultDB()
	v := Uimods{AppId: m.AppId}
	if err := o.Read(&v, "AppId"); err != nil {
		return err
	}
	m.UimodsId = v.UimodsId
	_, err := o.Update(m, fields...)
	return err
}

func DeleteUimodsById(uimodsId int64) (err error) {
	o := models.GetDefaultDB()
	v := Uimods{UimodsId: uimodsId}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

func DeleteUimodsByAppId(appId string) (err error) {
	o := models.GetDefaultDB()
	v := Uimods{AppId: appId}
	if err = o.Read(&v, "AppId"); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
